var allServices = new Array();
var limit = 17;
var default_pict_url = "http://auadult.com.au/default_pict/dft_icon.png";
//var default_pict_url = "http://192.168.1.154:8000/default_pict/dft_icon.png";

var SHOW_PICT_INTERVAL = 3000;
var SHOW_PICT_STOP_FLAG= 1;
var REFRESH_NUM = 0;

function sdist(ret_map,type){
  YUI().use('io-form','node',function(Y){
    var uri = ("/core/data/getservices/?tstmp={{TIME_STAMP}}");
    zoyoe.map = ret_map;
    function complete(io,o,args){
      var s_element = o.responseXML.documentElement.getElementsByTagName('SERVICE');
      for(var i=0;i<s_element.length;i++){
        var service = new Service(s_element[i]);
        if(type==service.type || type==''){
          ret_map.AddService(service);
          allServices.push(service);
        }
      }
      ret_map.ShiftZoom(true);
      // commented by mike
      if(!document.getElementById('iphone-warpper') && !document.getElementById('android-warpper')) {
        RefreshServicesInRightDock();//refresh for the first time
      }
      Microsoft.Maps.Events.addHandler(zoyoe.map.map, 'click', zoyoe.CloseShortCut);
/* 
      Move this into extensions 
      InitDrag();
      var scroll_h = Y.one('#right-bar-dock .div-scroll div.hscroll');
      var scroll_h_ele = Y.Node.getDOMNode(scroll_h);
      MarkAsScrollH(scroll_h_ele);
      var float_sh = Y.one('#float-info .div-scroll div.hscroll');
      var float_sh_ele = Y.Node.getDOMNode(float_sh);
      MarkAsScrollH(float_sh_ele);
      InitControlPanel();
*/
    }
    Y.on('io:complete',complete);
    var request = Y.io(uri);
  });
  return true;
}

function ResetShortCut(i){
  YUI().use('node',function(yui_node){
    var icon_containers = yui_node.all('#panel .gicon');
    var innerHTML = icon_containers.item(i).get('innerHTML');
    icon_containers.item(i).set('innerHTML','');
    icon_containers.item(i).set('innerHTML',innerHTML);
  });
}

function ShowServiceInRightDock(service,style,main_tag){
  YUI().use('node',function(node){
    var n = node.one('#panel .panel-left');
    if(!n){
      return;
    }
    // changed by mike for elimating reduplicate picture loading 20121010
    var use_default_pict = 0;
    if (service['grade'] in [1,2]){
      use_default_pict = 1;
    }

    var sdiv = null;
    if (!node.one('#iphone-warpper') && !node.one('#android-warpper')) {
          if(use_default_pict)
          sdiv = node.Node.create(
              "<a class='gicon' href = '/core/service/"+service.name+"/'" + "title='" + service.name + "'>"
              +"<img src='" + default_pict_url + "' class='shadow' ></img>"
              + "<span style='font-weight:bold'>" + service.name.replace('-', ' ') + "</span>"  //color:#FF0057
              + "<span>" + phoneformat(service.phone) + "</span>"
              + "<span>" + service.address + "</span>"
              +"</a>"
              );
        else
          sdiv = node.Node.create(
              "<a class='gicon' href = '/core/service/"+service.name+"/'" + "title='" + service.name + "'>"
              +"<img src='/gallery/imageicon/"+service.name+"/icon/?sc=true&cache=1' class='shadow' ></img>"
              + "<span style='font-weight:bold'>" + service.name.replace('-', ' ') + "</span>"  //color:#FF0057
              + "<span>" + phoneformat(service.phone) + "</span>"
              + "<span>" + service.address + "</span>"
              +"</a>"
              );
      n.append(sdiv); 
      node.Node.getDOMNode(sdiv).service = service;
    }else{
        if(use_default_pict){
          sdiv = node.Node.create(
              "<a class='gicon' href = '/core/service/"+service.name+"/'" + "title='" + service.name + "' id='" + default_pict_url + "'>"
              +"<span class='mobile-page-title' >" 
              + service.name.replace('-', ' ') + "</span><br>" 
              + "<span class='mobile-page-phone' >" + phoneformat(service.phone) + "</span>"
              +"</a>"
              );
        }
        else {
          sdiv = node.Node.create(
              "<a class='gicon' href = '/core/service/"+service.name+"/'" + "title='" + service.name + "' id='/gallery/imageicon/"+service.name+"/icon/?sc=true&cache=1'" + ">"
              +"<span class='mobile-page-title' >" 
              + service.name.replace('-', ' ')+ "</span><br>" 
              + "<span class='mobile-page-phone' >" + phoneformat(service.phone) + "</span>"
              +"</a>"
              );
        }
      n.append(sdiv); 
      node.Node.getDOMNode(sdiv).service = service;      
    }
  });
}

// added by mike 20121011
function showShopPictsAfterSeconds(flag) {
  // alert("show pictures ... ...");
  // alert("in time function " + flag);
  if(flag != SHOW_PICT_STOP_FLAG)
    return ;

  YUI().use('node',function(node){
    var n = node.all('#panel .iphone-panel-left a.gicon').each(
      function(shop, idx, lst) {
        // alert(shop.get('class'));
        var a = shop.get('innerHTML');
        // alert(a.match(/<img/)=="<img");
        if(!a.match(/<img/))
          shop.set('innerHTML', "<img src='" + shop.get("id") + "' class='shadow' ></img>" + a);
        // node.some_method();
        // alert(shop.get("title") + " " + shop.get("id") + " " + shop.get("href") + " " + shop.get('c'));
        // alert(shop.get('innerHTML'));
        // alert(shop.get("text"));
        // alert(shop.one("span").get("id"));
        // t.one();
        // alert(shop);
      });
    //alert("n is " + n);
  });
  YUI().use('node',function(node){
    var n = node.all('#panel .android-panel-left a.gicon').each(
      function(shop, idx, lst) {
        var a = shop.get('innerHTML');
        if(!a.match(/<img/))
          // alert(a + "<img src='" + shop.get("id") + " class='shadow' ></img>");
          shop.set('innerHTML', "<img src='" + shop.get("id") + "' class='shadow' ></img>" + a);
      });
  });
}


function RefreshServicesInRightDock(){
  YUI().use('node',function(node){

    var n = node.one('#panel .panel-left');
    if(n){
      // changed by mike for static display shop information 20121013
      //if(n.get('id') != 0 || n.get('id') != ''){
      if(n.get('id') == ''){
        n.set('id',1);         
        return;  
      }else{   
        n.set('innerHTML',"");
      }
      var main_tag = true;

/*    var eles = new Array();
      for(var i=0;i<groups.length;i++){
        if(groups[i].service_list.length != 0){
          var service = groups[i].service_list[0];
          if(service.active){
            eles.push(groups[i].service_list[0]);
            service.in_square = true;
          }
        }
      }
*/

      var fa = GetMapArea();
      var count = 0;
      var service;
      var gp;
      var displayedServices = [];
      for(var i=0;i<allServices.length;i++){
        service = allServices[i];
        gp = zoyoe.map.map.tryLocationToPixel(service.loc,Microsoft.Maps.PixelReference.page);
        //if(service.active){
          if(gp.x>=fa.left && gp.x<=fa.left+fa.width && gp.y>=fa.top && gp.y<=fa.top+fa.height){
            count++;
            if(count <= limit){
              displayedServices.push(service);
              //ShowServiceInRightDock(service,zoyoe.dock_style,main_tag);
              //main_tag = false;
            }
          }
        //}
      }

      //get the central point on the map
      centerX = fa.left + fa.width/2;
      centerY = fa.top + fa.height/2;
      var VIPs5Stars = [];
      var VIPs = [];
      var nonVIPs = [];

      //Separate VIPs5Stars, VIPs and nonVIPs
      for(var i=0;i<displayedServices.length;i++){
        if (displayedServices[i].grade == 5){
          VIPs5Stars.push(displayedServices[i]);
        }else if (displayedServices[i].grade == 4){
          VIPs.push(displayedServices[i]);
        }else{
          nonVIPs.push(displayedServices[i]);
        }
      }
      //sort and display VIPs5Stars      
      VIPs5Stars.sort(function(a,b){
        gpA = zoyoe.map.map.tryLocationToPixel(a.loc,Microsoft.Maps.PixelReference.page);
        gpB = zoyoe.map.map.tryLocationToPixel(b.loc,Microsoft.Maps.PixelReference.page);
        distanceA = getDistance(gpA.x, gpA.y, centerX, centerY);
        distanceB = getDistance(gpB.x, gpB.y, centerX, centerY);
        return distanceA-distanceB;
      });
      for(var j=0;j<VIPs5Stars.length;j++){
        ShowServiceInRightDock(VIPs5Stars[j],zoyoe.dock_style,main_tag);
        //main_tag = false;
      }
      //sort and display VIPs      
      VIPs.sort(function(a,b){
        gpA = zoyoe.map.map.tryLocationToPixel(a.loc,Microsoft.Maps.PixelReference.page);
        gpB = zoyoe.map.map.tryLocationToPixel(b.loc,Microsoft.Maps.PixelReference.page);
        distanceA = getDistance(gpA.x, gpA.y, centerX, centerY);
        distanceB = getDistance(gpB.x, gpB.y, centerX, centerY);
        return distanceA-distanceB;
      });
      for(var j=0;j<VIPs.length;j++){
        ShowServiceInRightDock(VIPs[j],zoyoe.dock_style,main_tag);
        //main_tag = false;
      }
      //sort and display nonVIPs      
      nonVIPs.sort(function(a,b){
        gpA = zoyoe.map.map.tryLocationToPixel(a.loc,Microsoft.Maps.PixelReference.page);
        gpB = zoyoe.map.map.tryLocationToPixel(b.loc,Microsoft.Maps.PixelReference.page);
        distanceA = getDistance(gpA.x, gpA.y, centerX, centerY);
        distanceB = getDistance(gpB.x, gpB.y, centerX, centerY);
        return distanceA-distanceB;
      });
      for(var j=0;j<nonVIPs.length;j++){
        ShowServiceInRightDock(nonVIPs[j],zoyoe.dock_style,main_tag);
        //main_tag = false;
      }

      YUI().use('node',function(node){
        var n = node.one('#panel .panel-left');
        var t = new Date().getTime();
        // alert(t);
        n.set("id",t);
        SHOW_PICT_STOP_FLAG = t;
        setTimeout("showShopPictsAfterSeconds(" + t + ")",SHOW_PICT_INTERVAL);
      });

      var header;
      var tail;
      if (allServices.length == 0){
/*
        header = node.Node.create("<a class='gicon-tools' style='padding:10px 6px 10px 6px;height:500px; border:none;background-color:black;color:white;'>" + 
"<span style='position:relative;left:80px;font-weight:bold;font-size:20px;color:#FF0057'>Instructions</span><br/><br/>" + 
"Move the map over a location and use the mouse scroll button to zoom in or out on that location. <br/><br/>Double click a location to center and zoom in on that location.<br/><br/>Click an adult service icon to see the details.<br/><br/>You can input an address into the search box to locate it on the map. The address can be a city name, suburb name, street name, postcode or full address.</a>");
*/
        header='';
      }else{
        if (!node.one('#iphone-warpper') && !node.one('#android-warpper') )
          header = node.Node.create("<a class='gicon-tools' id='search_result_count' style='padding:3px 0 0 3px;font-weight:bold;background-color:black;color:white;text-align:center;height:30px;font-size:20px;cursor:default;border-top:1px solid ghostWhite'>"+ count +" results</a>");
        else
          //header = node.Node.create("<a class='gicon-tools' style='padding:3px 0 0 3px;font-weight:bold;background-color:black;color:white;text-align:center;height:30px;font-size:20px'>"+ count +"  results</a>");
          header = node.Node.create("<a class='gicon-tools' id='search_result_count'>"+ count +" results</a>");
      }

      if(count > limit){
        tail = node.Node.create("<a class='gicon-tools' style='padding:5px 0 0 20px;font-weight:bold; background-color:black;'>"+"..."+"</a>");
      }

      n.append(tail);
      n.prepend(header);
    }
  });
}


 function ZoomIn(){
  var zoomLevel = zoyoe.map.map.getZoom() + 1;
  zoyoe.map.map.setView({ zoom: zoomLevel });
 }
 function ZoomOut(){
  var zoomLevel = zoyoe.map.map.getZoom() - 1;
  zoyoe.map.map.setView({ zoom: zoomLevel });
 }


/* goto functions: go to an address on the map according to user input*/
function goto(){
  var address = document.getElementById("theAddress").value;
  address = address.replace(/^\s+|\s+$/g, '') ;//trim head and tail spaces
  addressLower = address.toLowerCase();
/*
  if(addressLower == 'brisbane' 
  || addressLower == 'auburn'
  || addressLower == 'carlton'
  || addressLower == 'granville'
  || addressLower == 'greenacre'
  || addressLower == 'guildford'
  || addressLower == 'riverwood'
  || addressLower == 'liverpool'
  || addressLower == 'ashfield'){
    address = address + ", Australia";
  }
*/
  //if(addressLower == 'smithfield' || addressLower == 'broadway'){address = address + ", Sydney";}
  //if(addressLower == 'crows nest'){address = address + ", NSW";}
  //if(address!=''){address = address + ", Australia";}
  if(addressLower == 'smithfield, new south wales'){
    address = "Smithfield, Sydney, NSW";
  }
  //if(addressLower == 'city,sydney' || addressLower == 'city, sydney'){
  //  address = "Haymarket, New South Wales";
  //}

  var n = address.split(" ");
  var postcode = n[n.length-1];
  if (isDigit(postcode)){
    address = address.replace(postcode, "," + postcode);
  }

  //else if (address.substr(address.length-9,9).toLowerCase()!='australia'){
    //address = address + ", Australia";
  //}

  var credentials = "Av6myMPPl0Aix9wsk-YXGQ23bvY1A3I2dmHJ44GAVYwlF_70J4OJdmv_SqM1rFJd";
  var geocodeRequest = "http://dev.virtualearth.net/REST/v1/Locations?query=" + encodeURI(address) + "&output=json&jsonp=GeocodeCallback&key=" + credentials;
  CallRestService(geocodeRequest);
  document.getElementById("theAddress").blur();
}

var pinInfobox;
var pinInfoboxes=[];
function GeocodeCallback(result){
            //alert("Found location: " + result.resourceSets[0].resources[0].name);
            if (result &&
                   result.resourceSets &&
                   result.resourceSets.length > 0 &&
                   result.resourceSets[0].resources &&
                   result.resourceSets[0].resources.length > 0) 
            {
               document.getElementById("search-status-bar").innerHTML="Address Found";

               //alert(result.resourceSets[0].resources[0].address.locality);
               // Set the map view using the returned bounding box
               var bbox = result.resourceSets[0].resources[0].bbox;
               // alert("bounding box is " + bbox);
               
               var viewBoundaries = Microsoft.Maps.LocationRect.fromLocations(new Microsoft.Maps.Location(bbox[0], bbox[1]), new Microsoft.Maps.Location(bbox[2], bbox[3]));
               zoyoe.map.map.setView({ bounds: viewBoundaries});

               // Add a pushpin at the found location
               var location = new Microsoft.Maps.Location(result.resourceSets[0].resources[0].point.coordinates[0], result.resourceSets[0].resources[0].point.coordinates[1]);
               // alert(location);
               // alert(result.resourceSets[0].resources[0].point.coordinates[0]);
               // var newCenterLat = result.resourceSets[0].resources[0].point.coordinates[0];
               // var newCenterLong= result.resourceSets[0].resources[0].point.coordinates[1];
               // alert(newCenterLat -1 );

               var pushpin = new Microsoft.Maps.Pushpin(location);
               pinInfobox = new Microsoft.Maps.Infobox(location, { visible: true });
               pinInfoboxes.push(pinInfobox);
               pushpin.setOptions({icon:'/res/pushpin/pushpin_green.png',text:''});

               pushpin.Title = "";
               pushpin.Description = result.resourceSets[0].resources[0].name; //display the address

         // Add handler for the pushpin click event.
         Microsoft.Maps.Events.addHandler(pushpin, 'click', displayInfobox);

               zoyoe.map.map.entities.push(pushpin);
               zoyoe.map.map.entities.push(pinInfobox);

               //display pinInfobox for the first time
               pinInfobox.setOptions({title: '', description: pushpin.Description, location:location, visible:true, offset: new Microsoft.Maps.Point(0,10)});

         // Hide the infobox when the map is moved.
         //Microsoft.Maps.Events.addHandler(zoyoe.map.map, 'viewchange', hideInfobox);
         Microsoft.Maps.Events.addHandler(zoyoe.map.map, 'click', hideInfobox);

               // add by mike 20121016
              if(document.getElementById('iphone-warpper')){
                var newCenterLat = result.resourceSets[0].resources[0].point.coordinates[0] - 0.025;// -up, +down
                var newCenterLong= result.resourceSets[0].resources[0].point.coordinates[1] + 0.035;// +left, -right
                var newMapCenter = new Microsoft.Maps.Location(newCenterLat,newCenterLong);
                zoyoe.map.map.setView({center: newMapCenter,zoom:13}); 
              }

            }else{
              var address = document.getElementById("theAddress").value;
              if (address == "" || address == null) {
                document.getElementById("search-status-bar").innerHTML="Enter a location";
              }else{
                document.getElementById("search-status-bar").innerHTML="Address Not Found"; //
              }
              
            }
}

function CallRestService(request){
  var script = document.createElement("script");
  script.setAttribute("type", "text/javascript");
  script.setAttribute("src", request);
  document.body.appendChild(script);
}

function displayInfobox(e){
  pinInfobox.setOptions({title: e.target.Title, description: e.target.Description, visible:true, offset: new Microsoft.Maps.Point(0,10)});
  pinInfobox.setLocation(e.target.getLocation());
}                    

function hideInfobox(e){
  for(var i=0; i<pinInfoboxes.length; i++){
    pinInfoboxes[i].setOptions({ visible: false });
  }
}
/* end of goto functions */


function getDistance(x1,y1,x2,y2){
  xDiff = x2-x1;
  yDiff = y2-y1;
  return Math.pow((xDiff*xDiff + yDiff*yDiff),0.5);
}

function   isDigit(s){   
  var patrn=/^\d*$/;   
  return patrn.test(s) 
} 

function phoneformat(s){
  if(s.length == 10){
    if(s.substr(0,2)=="04"){
      return s.substr(0,4) + " " + s.substr(4,3) + " " + s.substr(7,3);
    }else{
      return s.substr(0,2) + " " + s.substr(2,4) + " " + s.substr(6,4);
    }
  }else{
    return s;
  }
}
//flash color
  var i = 1;
  function changecolor(a) {
  $(a).css("color",i==0?"ghostWhite":"#FF1143");
    i==2?i=0:i++;
  }
  $(function() {
    //$('#shop_gallery a').lightBox();
    setInterval(function(){ changecolor("#search_result_count")},300) //半秒运行一次
  });